package org.xuk.spring.ws.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;

import java.util.Date;

@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class TokenUtil {
    private static final String SECRET = "secret hello";
    /**
     * jwt token失效时间
     */
    private static final Long TOKEN_EXPIRED = 7200 * 1000L;

    /**
     * 解析token
     *
     * @param token
     * @return
     */
    public static String parseToken(String token) {
        Claims claims = Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token)
                .getBody();
        return claims.getSubject();
    }

    /**
     * 生成token
     *
     * @param subjectId
     * @return
     */
    public static String generateToken(String subjectId) {
        JwtBuilder jwtBuilder = Jwts.builder().setSubject(subjectId).setExpiration(new Date(System.currentTimeMillis() + TOKEN_EXPIRED))
                .setIssuedAt(new Date())
                .signWith(SignatureAlgorithm.HS256, SECRET);
        return jwtBuilder.compact();
    }
}
